import logging

from selenium.webdriver.common.by import By

from base.app.base_page import BasePage

# 对象库层
from utils import UtilsDriver


class IndexPage(BasePage):
    def __init__(self):
        super().__init__()
        # 频道区域
        self.channel_area = (By.CLASS_NAME, "android.widget.HorizontalScrollView")
        # 具体频道
        self.channel_name = (By.XPATH, "//*[contains(@text,'{}')]")

    # 找到频道区域
    def find_channel_area(self):
        return self.fd_em(self.channel_area)

    # 找到具体频道
    def find_channel_name(self, ch_name):
        return self.driver.find_element(self.channel_name[0], self.channel_name[1].format(ch_name))


# 操作层
class IndexHandle:

    def __init__(self):
        self.index_page = IndexPage()

    # 选择频道
    def check_channel(self, ch_name):
        # 滑动坐标计算
        # 获取频道区域的元素对象大小和位置
        ch_size = self.index_page.find_channel_area().size
        ch_location = self.index_page.find_channel_area().location
        # 起始横坐标
        start_x = ch_size['width'] * 0.8 + ch_location['x']
        # 起始纵坐标
        start_y = ch_size['height'] * 0.5 + ch_location['y']
        # 结束横坐标
        end_x = ch_size['width'] * 0.2 + ch_location['x']
        # 结束纵坐标
        end_y = start_y

        while True:
            try:
                # 1.找指定的频道对象,如果找的到则直接点击
                self.index_page.find_channel_name(ch_name).click()
                break
            # 2.如果找不到指定的频道则会抛出异常
            except Exception as e:
                # 滑动之前获取一次页面信息
                old_page = UtilsDriver.get_app_driver().page_source
                # 3.滑动一次区域
                UtilsDriver.get_app_driver().swipe(start_x=start_x, start_y=start_y, end_x=end_x, end_y=end_y,
                                                   duration=3000)
                # 滑动之后获取一次页面信息
                new_page = UtilsDriver.get_app_driver().page_source
                # 4.如果滑动之前和之后页面信息一致则表示滑动到最底部了还没找到想要的频道
                if old_page == new_page:
                    logging.error("滑动到最底部,没有找到名称为{}的频道".format(ch_name))
                    break

# 业务层
class IndexProxy:
    def __init__(self):
        self.index_handle = IndexHandle()

    # 选择频道
    def check_cl(self,ch_name):
        self.index_handle.check_channel(ch_name)